const express = require('express')
const pool = require('../test_pool.js')
const test_router = express.Router()

test_router.post('/login',(req,res,next)=>{
	pool.query('select * from user where uname=? or phone=? and upwd=? ',[req.body.uname,req.body.uname,req.body.upwd],(err,suc)=>{
		if (err){
			next(err)
			return
		}
		if(suc.length){
			res.send({code:1,title:'登陆成功',user:suc[0].uname,uid:suc[0].id})
		}else{
			res.send({code:0,title:'登陆失败'})
		}
	})
})

test_router.post('/reg/name',(req,res,next)=>{
	pool.query('select uname from user where uname = ?',[req.body.uname],(err,suc)=>{
		if (err){
			next(err)
			return
		}
		if(!suc.length){
			res.send({code:1,title:'用户名可用'})
		}else{
			res.send({code:0,title:'用户名已存在'})
		}
	})
})

test_router.post('/reg/phone',(req,res,next)=>{
	pool.query('select phone from user where phone = ?',[req.body.uphone],(err,suc)=>{
		if (err){
			next(err)
			return
		}
		if(!suc.length){
			res.send({code:1,title:'手机号可用'})
		}else{
			res.send({code:0,title:'手机号已存在'})
		}
	})
})

test_router.post('/reg/creg',(req,res,next)=>{
	pool.query('select uname from user where uname = ?',[req.body.uname],(err,suc)=>{
		if (err){
			next(err)
			return
		}
		if(!suc.length){
			pool.query('select phone from user where phone = ?',[req.body.uphone],(err,suc)=>{
				if (err){
					next(err)
					return
				}
				if(!suc.length){
					pool.query('insert into user value(null,?,?,?)',[req.body.uname,req.body.upwd,req.body.uphone],(err,suc)=>{
						if (err){
							next(err)
							return
						}
						if(!suc.length){
							res.send({code:1,title:'注册成功'})
						}else{
							res.send({code:0,title:'注册失败,请重新核对信息'})
						}
					})
				}else{
					res.send({code:0,title:'手机号已存在'})
				}
			})
		}else{
			res.send({code:0,title:'用户名已存在'})
		}
	})
})

module.exports = test_router